function generateSudoku(difficulty = 'medium') {
    // 初始化空棋盘
    const board = Array(9).fill().map(() => Array(9).fill(0));
    
    // 填充对角线上的3个3x3方块
    for (let i = 0; i < 9; i += 3) {
        fillBox(board, i, i);
    }
    
    // 填充剩余格子
    solveSudoku(board);
    
    // 根据难度移除数字
    const difficulties = {
        easy: 35,
        medium: 45,
        hard: 55
    };
    
    const cellsToRemove = difficulties[difficulty] || difficulties.medium;
    removeNumbers(board, cellsToRemove);
    
    return board;
}

function fillBox(board, row, col) {
    const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            const randomIndex = Math.floor(Math.random() * numbers.length);
            board[row + i][col + j] = numbers[randomIndex];
            numbers.splice(randomIndex, 1);
        }
    }
}

function solveSudoku(board) {
    const emptyCell = findEmptyCell(board);
    if (!emptyCell) return true;
    
    const [row, col] = emptyCell;
    for (let num = 1; num <= 9; num++) {
        if (isValid(board, row, col, num)) {
            board[row][col] = num;
            if (solveSudoku(board)) return true;
            board[row][col] = 0;
        }
    }
    return false;
}

function removeNumbers(board, count) {
    let removed = 0;
    while (removed < count) {
        const row = Math.floor(Math.random() * 9);
        const col = Math.floor(Math.random() * 9);
        if (board[row][col] !== 0) {
            board[row][col] = 0;
            removed++;
        }
    }
}

function findEmptyCell(board) {
    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            if (board[i][j] === 0) return [i, j];
        }
    }
    return null;
}

function isValid(board, row, col, num) {
    // 检查行
    for (let x = 0; x < 9; x++) {
        if (board[row][x] === num) return false;
    }
    
    // 检查列
    for (let x = 0; x < 9; x++) {
        if (board[x][col] === num) return false;
    }
    
    // 检查3x3方块
    const startRow = Math.floor(row / 3) * 3;
    const startCol = Math.floor(col / 3) * 3;
    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            if (board[i + startRow][j + startCol] === num) return false;
        }
    }
    
    return true;
}

function getSolution(board) {
    const solution = JSON.parse(JSON.stringify(board));
    solveSudoku(solution);
    return solution;
}

module.exports = {
    generateSudoku,
    isValid,
    getSolution
}; 